package com.sixbro.file.storage.controller;

import cn.hutool.core.lang.Dict;
import com.sixbro.file.storage.entity.FileDocument;
import com.sixbro.file.storage.service.impl.LocalFileStorageServiceImpl;
import com.sixbro.file.storage.service.impl.QiNiuFileStorageServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 文件上传 Controller
 * </p>
 *
 * @Author: Mr.Lu
 * @Since: 2020/6/23 14:15
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    private final LocalFileStorageServiceImpl localFileStorageService;

    private final QiNiuFileStorageServiceImpl qiNiuFileStorageService;

    @Autowired
    public UploadController(LocalFileStorageServiceImpl localFileStorageService, QiNiuFileStorageServiceImpl qiNiuFileStorageService) {
        this.localFileStorageService = localFileStorageService;

        this.qiNiuFileStorageService = qiNiuFileStorageService;
    }

    @PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Dict local(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Dict.create().set("code", 400).set("message", "文件内容为空");
        }

        try {
            FileDocument document = localFileStorageService.upload(file);
            return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", document.getFilename()).set("filePath", document.getUrl()));
        } catch (IOException e) {
            return Dict.create().set("code", 500).set("message", "文件上传失败");
        }
    }

    @PostMapping(value = "/yun", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Dict yun(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Dict.create().set("code", 400).set("message", "文件内容为空");
        }
        try {
            FileDocument document = qiNiuFileStorageService.upload(file);
            return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", document.getFilename()).set("filePath", document.getUrl()));
        } catch (IOException e) {
            return Dict.create().set("code", 500).set("message", "文件上传失败");
        }
    }
}
